package com.dianxin.farm.util.util;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * @auther xukai
 * @date 2020/10/8.
 */
public class HttpsUtil {



        /**
         * httpsRequest https的请求方式
         *
         * @author 81046
         * @date 2018年4月18日下午3:55:14
         * @param Url
         * @param method
         * @param outStr
         * @return
         */
        public static String httpsRequest(String Url, String method, String outStr) {
            StringBuffer buffer = null;
            try {
                SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
                TrustManager[] tm = { new MyX509TrustManager() };
// 初始化
                sslContext.init(null, tm, new java.security.SecureRandom());
// 获取sslSocketFactory对象
                SSLSocketFactory ssf = sslContext.getSocketFactory();
// 建立连接
                URL url = new URL(Url);
                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setRequestMethod(method);
// 设置当前实例使用sslSocketFactory
                conn.setSSLSocketFactory(ssf);
                conn.setDoOutput(true);
                conn.connect();
// 先写入数据，再读取数据
                if (outStr != null) {
                    OutputStream os = conn.getOutputStream();
                    os.write(outStr.getBytes("UTF-8"));
                    os.close();
                }
// 读取服务端的内容
                InputStream is = conn.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "UTF-8");
                BufferedReader br = new BufferedReader(isr);
                buffer = new StringBuffer();
                String line = null;
                while ((line = br.readLine()) != null) {
                    buffer.append(line);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchProviderException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            }
            return buffer.toString();
        }
}
